package com.moku.tester;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.TimerTask;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.io.StreamConnection;

import net.rim.device.api.i18n.SimpleDateFormat;
import net.rim.device.api.notification.NotificationsManager;
import net.rim.device.api.system.EventLogger;
import net.rim.device.api.system.LED;
import net.rim.device.api.system.RadioInfo;
import net.rim.device.api.ui.UiApplication;

public class TestTask extends TimerTask {

	private TestOptionsScreen _testOptionsScreen;

	public TestTask(TestOptionsScreen testOptionsScreen) {
		_testOptionsScreen = testOptionsScreen;
	}

	// Shutdown the thread.
	public void stop() {
		disableAlarm();
	}

	private boolean chkCoverage() {
		int state = RadioInfo.getState() & RadioInfo.STATE_ON;
		int data = RadioInfo.getNetworkService()
				& RadioInfo.NETWORK_SERVICE_DATA;

		if ((state > 0) && (data > 0))
			return true;

		return false;
	}

	public void run() {

		// This entire block is synchronized, this ensures I won't miss
		// fetch requests
		// made while I process a page.
		synchronized (this) {
			// Open the connection and extract the data.
			StringBuffer msg = new StringBuffer("Test Time ");
			msg.append(new SimpleDateFormat("yyyy-MM-dd HH:mm")
					.format(new Date()));

			if (_testOptionsScreen.isRadioTestCheck()) {
				radioTest(msg);
			}

			if (_testOptionsScreen.isHttpGetTestCheck()) {
				httpGetTest(msg);
			}

			updateContent(msg.toString());

		}
	}

	private void radioTest(StringBuffer msg) {
		// check radio
		if (!chkCoverage()) {
			msg.append("\n[Radio Test]\nNo network service!\n");
			alarm("[Radio Test]\nNo network service!");
		} else {
			// get(msg);
			msg.append("\n[Radio Test]\nNetworkName: ");
			msg.append(RadioInfo.getCurrentNetworkName());
			msg.append("\nSignal: ");
			msg.append(RadioInfo.getSignalLevel());
			msg.append(" dBm");
			msg.append("\nReceived Packets: ");
			msg.append(RadioInfo.getNumberOfPacketsReceived());
			msg.append("\nSent Packets: ");
			msg.append(RadioInfo.getNumberOfPacketsSent());
		}
	}

	private void httpGetTest(StringBuffer msg) {
		msg.append("\n[Http GET Test]\n");

		try {
			StreamConnection s = null;
			s = (StreamConnection) Connector.open(_testOptionsScreen
					.getHttpUrl());
			HttpConnection httpConn = (HttpConnection) s;

			int status = httpConn.getResponseCode();

			if (status == HttpConnection.HTTP_OK) {

				InputStream input = s.openInputStream();

				byte[] data = new byte[256];
				int len = 0;
				int size = 0;

				while (-1 != (len = input.read(data))) {
					size += len;
				}
				input.close();

				msg.append("response code = ");
				msg.append(status);
				msg.append("\n");
				msg.append(size);
				msg.append("bytes received]\n");
			} else {
				msg.append("response code = ");
				msg.append(status);
			}

			s.close();

		} catch (IOException e) {
			msg.append(e.getMessage());
			alarm(e.getMessage());
		}
	}

	public void updateContent(final String content) {
		HttpTester theApp = (HttpTester) UiApplication.getUiApplication();
		final HttpTesterScreen mainScreen = theApp.getHttpTesterScreen();
		UiApplication.getUiApplication().invokeLater(new Runnable() {
			public void run() {
				mainScreen.getRichTextField().setText(content);
			}
		});
	}

	public void disableAlarm() {
		LED.setState(LED.STATE_OFF);
	}

	private void alarm(String msg) {
		// log warning
		EventLogger
				.logEvent(HttpTester.ID, msg.getBytes(), EventLogger.WARNING);

		NotificationsManager
				.triggerImmediateEvent(HttpTester.ID, 0, this, null);
	}

}
